package level

import (
	"context"

	"mall/common/moneyx"
	"mall/service/backend/api/internal/logic/member/util"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type MemberLevelListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMemberLevelListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MemberLevelListLogic {
	return &MemberLevelListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MemberLevelListLogic) MemberLevelList(req *types.MemberLevelListReq) (resp *types.MemberLevelListResp, err error) {
	var page int64 = 1
	var pageSize int64
	if req.Current > 1 {
		page = req.Current
	}
	if req.PageSize > 0 { // 指定，检查最大值
		pageSize = req.PageSize
		if pageSize > l.svcCtx.Config.Query.MaxAmount {
			pageSize = l.svcCtx.Config.Query.MaxAmount
		}
	} else { // 不指定，使用默认值
		pageSize = l.svcCtx.Config.Query.DefaultAmount
	}

	orderBys := util.ParseBackendSorter(req.Sorter)
	filterBys := util.ParseBackendFilter(req.Filter)
	res, err := l.svcCtx.BackendRpc.MemberLevelList(l.ctx, &backendclient.MemberLevelListReq{
		Current:  page,
		PageSize: pageSize,
		Name:     req.Name,
		Slug:     req.Slug,
		Search:   req.Search,
		OrderBy:  orderBys,
		FilterBy: filterBys,
	})
	if err != nil {
		return nil, err
	}

	var list []*types.MemberLevelInfo
	if len(res.List) > 0 {
		for _, item := range res.List {
			list = append(list, &types.MemberLevelInfo{
				Id:                 item.Id,
				Name:               item.Name,
				Slug:               item.Slug,
				Desc:               item.Desc,
				MediaId:            item.MediaId,
				MediaUrl:           item.MediaUrl,
				Integral:           item.Integral,
				WithMemberPrice:    item.WithMemberPrice > 0,
				WithPromotion:      item.WithPromotion > 0,
				WithFreeFreight:    item.WithFreeFreight > 0,
				WithComment:        item.WithComment > 0,
				WithSignIn:         item.WithSignIn > 0,
				WithBirthday:       item.WithBirthday > 0,
				FreeFreightAmount:  moneyx.FormatAmount(int64(item.FreeFreight)),
				IntegralForComment: item.IntegralForComment,
				TaskCount:          item.TaskCount,
				IsDefault:          item.IsDefault > 0,
			})
		}
	}

	return &types.MemberLevelListResp{
		Current:  page,
		PageSize: pageSize,
		List:     list,
		Total:    res.Total,
	}, nil
}
